package cn.wawi.common.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import cn.wawi.common.annotation.Permission;
import cn.wawi.dao.sys.PrivilegeDao;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.entity.sys.User;

/**
 * @description 全局视图拦截器，页面展示之前做一些通用处理实现权限拦截
 * @version V1.0.0
 * @author 龚亮
 * @date 2015-05-24 08:14:55
 */
public class GlobalInterceptor extends HandlerInterceptorAdapter {
	
	@Resource
	protected PrivilegeDao<Privilege> privilegeDao;

	
	//在action返回视图后执行
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception e){
	}
	//在执行action里面的逻辑后返回视图之前执行
	public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView view){
		//String path=request.getContextPath();
		//String url=request.getRequestURL().toString();
		//String uri=request.getRequestURI();
	}

	//在执行action里面的处理逻辑之前执行
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
	  User user=(User) request.getSession().getAttribute("loginUser");
	  String url=request.getRequestURL().toString();
	  if(url.contains("/sys_user/login")||url.contains("/static/")||url.contains("/plugins/")||url.contains("/ueditor/")){
		  return true;
	  }
	  if(user==null){
		  response.sendRedirect(request.getContextPath());  
		  return false;
	  }
	  if(handler instanceof HandlerMethod){
		  HandlerMethod method = (HandlerMethod)handler;
		  Permission permission = method.getMethodAnnotation(Permission.class);
		  if(null==permission){//无注解表示可以匿名访问
		      return true;
		  }else{   //有注解时,判断是否有权限
			  if(hasPermission(user,permission.value())){
				  return true;
			  }else{
				  response.sendRedirect(request.getContextPath()+"/error/noPermission.html"); 
				  return false;
			  }
		  }
	   }
	   return true;
	}
	public boolean hasPermission(User user,String permission){
		boolean flag=false;
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("userId",user.getId());
		map.put("type","o");
		List<Privilege> list=privilegeDao.findUserPermission(map);
		for(Privilege p: list){
			if(p.getPermCode().contains(permission)){
				flag=true;
				break;
			}
		}
		return flag;
	}
}
